<template>
  <div class="article-list">
    <h1>文章管理</h1>
    
    <div class="button-group">
      <router-link :to="`/article/create`" class="btn btn-success">
        创建新文章
      </router-link>
      
      <div class="filter-options">
        <button 
          class="btn" 
          :class="{'btn-active': displayMode === 'published'}" 
          @click="switchDisplayMode('published')"
        >
          已发布文章
        </button>
        <button 
          class="btn" 
          :class="{'btn-active': displayMode === 'draft'}" 
          @click="switchDisplayMode('draft')"
        >
          草稿箱
        </button>
        <button 
          class="btn" 
          :class="{'btn-active': displayMode === 'all'}" 
          @click="switchDisplayMode('all')"
        >
          全部
        </button>
      </div>
    </div>
    
    <div v-if="loading" class="loading">正在加载文章列表...</div>
    <div v-if="error" class="error">{{ error }}</div>
    <div v-if="deleteSuccess" class="success">文章已成功删除！</div>
    
    <div v-if="!loading && filteredArticles.length === 0" class="empty-list">
      {{ emptyMessage }}
    </div>
    
    <div v-if="filteredArticles.length > 0" class="article-cards">
      <div 
        v-for="article in filteredArticles" 
        :key="article.id"
        class="article-card"
      >
        <div class="article-cover" v-if="article.coverImage">
          <img :src="getImageUrl(article.coverImage)" :alt="article.title">
        </div>
        <div class="article-info">
          <div class="status-badge" :class="article.status">
            {{ article.status === 'published' ? '已发布' : '草稿' }}
          </div>
          <h2>{{ article.title }}</h2>
          <div class="meta-info">
            <span class="author" v-if="article.author">作者: {{ article.author }}</span>
            <span class="publish-time" v-if="article.publishTime">发布于: {{ formatDate(article.publishTime) }}</span>
            <span class="view-count">阅读: {{ article.viewCount || 0 }}</span>
          </div>
          <p class="description" v-if="article.content">
            {{ getContentPreview(article.content) }}
          </p>
          <div class="tags" v-if="article.tags">
            <span v-for="(tag, index) in getTagArray(article.tags)" :key="index" class="tag">{{ tag }}</span>
          </div>
          <div class="button-group">
            <router-link 
              :to="`/article/view/${article.id}`" 
              class="btn btn-primary"
            >
              查看详情
            </router-link>
            <router-link 
              :to="`/article/edit/${article.id}`" 
              class="btn btn-warning"
            >
              编辑文章
            </router-link>
            <button 
              v-if="article.status === 'draft'"
              class="btn btn-publish" 
              @click="publishArticle(article)"
            >
              立即发布
            </button>
            <button 
              class="btn btn-danger" 
              @click="confirmDelete(article)"
            >
              删除文章
            </button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 删除确认对话框 -->
    <div v-if="showDeleteConfirm" class="modal-backdrop">
      <div class="modal-content">
        <h3>确认删除</h3>
        <p>您确定要删除文章 "{{ selectedArticle.title }}" 吗？</p>
        <p class="warning">此操作不可撤销，文章将被永久删除。</p>
        <div class="modal-buttons">
          <button class="btn btn-secondary" @click="cancelDelete">取消</button>
          <button class="btn btn-danger" @click="deleteArticle" :disabled="deleting">
            {{ deleting ? '删除中...' : '确认删除' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, onMounted, computed } from 'vue';

export default defineComponent({
  setup() {
    const articles = ref([]);
    const loading = ref(true);
    const error = ref('');
    const deleteSuccess = ref(false);
    const showDeleteConfirm = ref(false);
    const selectedArticle = ref({});
    const deleting = ref(false);
    const publishing = ref(false);
    const displayMode = ref('published'); // 'published', 'draft', 'all'
    
    const filteredArticles = computed(() => {
      const arr = Array.isArray(articles.value) ? articles.value : [];
      if (displayMode.value === 'all') {
        return arr;
      } else if (displayMode.value === 'published') {
        return arr.filter(article => article.status === 'published');
      } else {
        return arr.filter(article => article.status === 'draft');
      }
    });
    
    const emptyMessage = computed(() => {
      if (displayMode.value === 'published') {
        return '暂无已发布文章，点击"创建新文章"按钮添加';
      } else if (displayMode.value === 'draft') {
        return '暂无草稿文章';
      } else {
        return '暂无文章';
      }
    });
    
    const switchDisplayMode = (mode) => {
      displayMode.value = mode;
      fetchArticles(mode);
    };
    
    const fetchArticles = async (mode = displayMode.value) => {
      loading.value = true;
      error.value = '';
      
      try {
        let endpoint = '/list';
        if (mode === 'draft') {
          endpoint = '/drafts';
        } else if (mode === 'all') {
          endpoint = '/all';
        }
        
        const response = await fetch(`http://localhost:9001/api/article${endpoint}`);
        if (!response.ok) {
          throw new Error('获取文章列表失败');
        }
        
        const data = await response.json();
        // 修复：根据接口返回结构赋值
        if (mode === 'all' || mode === 'draft') {
          // /all 和 /drafts 返回的是数组
          articles.value = Array.isArray(data) ? data : [];
        } else {
          // /list 返回的是 { code, data: { list, total }, msg }
          if (data && data.code === 1 && data.data && Array.isArray(data.data.list)) {
            articles.value = data.data.list;
          } else {
            articles.value = [];
          }
        }
      } catch (err) {
        console.error('获取文章列表时出错:', err);
        error.value = '加载文章失败: ' + err.message;
      } finally {
        loading.value = false;
      }
    };
    
    const publishArticle = async (article) => {
      if (publishing.value) return;
      
      publishing.value = true;
      error.value = '';
      
      try {
        const response = await fetch(`http://localhost:9001/api/article/publish/${article.id}`, {
          method: 'PUT'
        });
        
        if (!response.ok) {
          throw new Error('发布文章失败');
        }
        
        // 更新文章状态
        const updatedArticle = await response.json();
        const index = articles.value.findIndex(a => a.id === updatedArticle.id);
        if (index !== -1) {
          articles.value[index] = updatedArticle;
        }
        
        // 显示成功消息
        deleteSuccess.value = '文章已成功发布';
        setTimeout(() => {
          deleteSuccess.value = false;
        }, 3000);
      } catch (err) {
        console.error('发布文章时出错:', err);
        error.value = '发布文章失败: ' + err.message;
      } finally {
        publishing.value = false;
      }
    };
    
    const formatDate = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN', { 
        year: 'numeric', 
        month: 'long', 
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      });
    };
    
    const getContentPreview = (content) => {
      // 从Markdown中提取纯文本预览
      const plainText = content.replace(/[#*`_~]/g, '').replace(/\n/g, ' ');
      return plainText.length > 100 ? plainText.substring(0, 100) + '...' : plainText;
    };
    
    const getTagArray = (tagsString) => {
      return tagsString ? tagsString.split(',').map(tag => tag.trim()) : [];
    };
    
    const getImageUrl = (path) => {
      if (!path) return '';
      if (/^https?:\/\//.test(path)) return path;
      if (!path.startsWith('/image')) {
        return '/image' + path.replace(/^\/static/, '');
      }
      return path;
    };
    
    const confirmDelete = (article) => {
      selectedArticle.value = article;
      showDeleteConfirm.value = true;
    };
    
    const cancelDelete = () => {
      showDeleteConfirm.value = false;
      selectedArticle.value = {};
    };
    
    const deleteArticle = async () => {
      if (!selectedArticle.value.id) return;
      
      deleting.value = true;
      error.value = '';
      
      try {
        const response = await fetch(`http://localhost:9001/api/article/delete/${selectedArticle.value.id}`, {
          method: 'DELETE'
        });
        
        if (!response.ok) {
          throw new Error('删除文章失败');
        }
        
        // 从列表中移除已删除的文章
        articles.value = articles.value.filter(a => a.id !== selectedArticle.value.id);
        
        // 显示成功消息
        deleteSuccess.value = true;
        setTimeout(() => {
          deleteSuccess.value = false;
        }, 3000);
        
        // 关闭确认对话框
        showDeleteConfirm.value = false;
        selectedArticle.value = {};
      } catch (err) {
        console.error('删除文章时出错:', err);
        error.value = '删除文章失败: ' + err.message;
      } finally {
        deleting.value = false;
      }
    };
    
    onMounted(() => {
      fetchArticles();
    });
    
    return {
      articles,
      filteredArticles,
      loading,
      error,
      deleteSuccess,
      showDeleteConfirm,
      selectedArticle,
      deleting,
      publishing,
      displayMode,
      emptyMessage,
      formatDate,
      getContentPreview,
      getTagArray,
      getImageUrl,
      confirmDelete,
      cancelDelete,
      deleteArticle,
      publishArticle,
      switchDisplayMode
    };
  }
});
</script>

<style scoped>
.article-list {
  max-width: 960px;
  margin: 0 auto;
  padding: 20px;
}

h1 {
  margin-bottom: 20px;
  border-bottom: 2px solid #eee;
  padding-bottom: 10px;
}

.button-group {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
}

.filter-options {
  display: flex;
  gap: 10px;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  text-decoration: none;
  font-size: 14px;
  display: inline-block;
  background-color: #f0f0f0;
  color: #333;
}

.btn-active {
  background-color: #4CAF50;
  color: white;
}

.btn-success {
  background-color: #4CAF50;
  color: white;
}

.btn-primary {
  background-color: #2196F3;
  color: white;
}

.btn-warning {
  background-color: #FF9800;
  color: white;
}

.btn-publish {
  background-color: #4CAF50;
  color: white;
}

.btn-danger {
  background-color: #f44336;
  color: white;
}

.btn-secondary {
  background-color: #9e9e9e;
  color: white;
}

.empty-list {
  text-align: center;
  padding: 40px;
  background-color: #f9f9f9;
  border-radius: 4px;
  margin-top: 20px;
  font-size: 16px;
  color: #666;
}

.article-cards {
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-top: 20px;
}

.article-card {
  border: 1px solid #eee;
  border-radius: 4px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  display: flex;
  overflow: hidden;
  position: relative;
}

.status-badge {
  position: absolute;
  top: 10px;
  right: 10px;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: bold;
}

.status-badge.published {
  background-color: #e8f5e9;
  color: #2e7d32;
}

.status-badge.draft {
  background-color: #fff3e0;
  color: #e65100;
}

.article-cover {
  flex: 0 0 200px;
  overflow: hidden;
}

.article-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.article-info {
  flex: 1;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.article-info h2 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 20px;
}

.meta-info {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.status {
  font-weight: bold;
}

.status.published {
  color: #4CAF50;
}

.status.draft {
  color: #FFC107;
}

.description {
  margin-bottom: 15px;
  color: #444;
  line-height: 1.5;
}

.tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 15px;
}

.tag {
  background-color: #e0e0e0;
  color: #333;
  padding: 4px 8px;
  border-radius: 16px;
  font-size: 12px;
}

.loading, .error, .success {
  padding: 10px;
  margin-bottom: 15px;
  border-radius: 4px;
}

.loading {
  background-color: #f9f9f9;
}

.error {
  background-color: #ffebee;
  color: #c62828;
}

.success {
  background-color: #e8f5e9;
  color: #2e7d32;
}

/* 模态框样式 */
.modal-backdrop {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 4px;
  width: 90%;
  max-width: 500px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.modal-content h3 {
  margin-top: 0;
}

.modal-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.warning {
  color: #f44336;
  font-weight: bold;
}

@media (max-width: 768px) {
  .article-card {
    flex-direction: column;
  }
  
  .article-cover {
    flex: 0 0 auto;
    height: 200px;
  }
  
  .button-group {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-options {
    margin-top: 10px;
    justify-content: center;
  }
}
</style> 